/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-03-19
 * Time: 14:27
 */
public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val){
            this.val = val;
        }
    }

    //当前搜索树的根节点
    public TreeNode root = null;

    public TreeNode search(int val) {
        TreeNode cur = root;
        while (cur != null){
            if (cur.val < val){
                cur = cur.right;
            }else if (cur.val > val){
                cur = cur.left;
            }else {
                return cur;
            }
        }
        return null;
    }

    public void insert(int val){
        TreeNode newNode = new TreeNode(val);
        if (root == null){
            root = newNode;
            return;
        }

        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null){
            if (cur.val < val){
                parent = cur;
                cur = cur.right;
            }else if (cur.val > val){
                parent = cur;
                cur = cur.left;
            }else {
                return;
            }
        }
        if (parent.val < val){
            parent.right = newNode;
        }else {
            parent.left = newNode;
        }
    }

    public void remove(int val){
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null){
            if (cur.val < val){
                parent = cur;
                cur = cur.right;
            }else if (cur.val > val){
                parent = cur;
                cur = cur.left;
            }else {
                removeNode(cur,parent);
                return;
            }
        }
    }
    private void removeNode(TreeNode cur,TreeNode parent){
        if (cur.left == null){
            if (cur == root){
                root = root.right;
            }else if (cur == parent.left){
                parent.left = cur.right;
            }else {
                //if(cur == parent.right)
                parent.right = cur.right;
            }
        }else if (cur.right == null){
                if (cur == root){
                    root = cur.left;
                }else if (cur == parent.left){
                    parent.left = cur.left;
                }else {
                    parent.right = cur.left;
                }
        }else {
            TreeNode target = cur.right;
            TreeNode targetParent = cur;
            while (target.left != null){
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if (target == targetParent.left){
                targetParent.left = target.right;
            }else {
                targetParent.right = target.right;
            }
        }
    }
}




























